package com.gwsdk.paysdk.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.acitvityV2.GWWebViewActivity;
import com.gwsdk.paysdk.bean.SdkDomain;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.config.GWConstant;
import com.gwsdk.paysdk.dialog.GWLoadDialog;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 描述：工具类
 * 作者：钮家齐
 * 时间: 2018-09-21 9:32
 */

public class AppUtils {

    /**
     * Regex of email.
     */
    public static final String REGEX_EMAIL         = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    private static HttpURLConnection conn;

    public static void initActionBarPosition(Activity activity, ImageView view) {
        boolean setTranslucent = setTranslucent(activity);
        if (setTranslucent == true) {
            int height = getStatusHeight(activity);
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.height = height;
            view.setLayoutParams(layoutParams);
        } else {
            return;
        }
    }

    /**
     * 图片去色,返回灰度图片
     * @param bmpOriginal 传入的图片
     * @return 去色后的图片
     */
    public static Bitmap toGrayScale(Bitmap bmpOriginal) {
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();

        Bitmap bmpGrayScale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayScale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayScale;
    }

    public static void returnBitMap(final String url1){
        new Thread(new Runnable() {
            @Override
            public void run() {

                if (TextUtils.isEmpty(url1)) {
                    GWLog.e("分享数据logo", "imageURL is null");
                    return;
                }
                URL url = null;
                InputStream is = null;
                try {
                    url = new URL(url1);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        is = conn.getInputStream();
                        Constant.ShareBitmap = BitmapFactory.decodeStream(is);

                        if (Constant.ShareBitmap == null){
                            GWLog.e("分享数据logo", "BitmapFactory.decodeStream is null");
                            return;
                        }

                        Bitmap thumbBmp = Bitmap.createScaledBitmap(Constant.ShareBitmap, 150, 150, true);
                        Constant.ShareBitmap = thumbBmp;
                        for (int imageSize = 0, quality = 100; imageSize > 31; quality--) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            thumbBmp.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                            byte[] bytes = baos.toByteArray();
                            Constant.ShareBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                            imageSize = bytes.length / 1024;
                            GWLog.e("wechat", "压缩后图片的大小" + (Constant.ShareBitmap.getByteCount() / 1024 / 1024)
                                    + "M宽度为" + Constant.ShareBitmap.getWidth() + "高度为" + Constant.ShareBitmap.getHeight()
                                    + "bytes.length=  " + (bytes.length / 1024) + "KB"
                                    + "quality=" + quality);

                        }
                    }
                } catch (MalformedURLException e) {
                    Constant.ShareBitmap = null;
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 使状态栏透明 * <p> * 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity
     */
    private static boolean setTranslucent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            //activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param activity
     * @return > 0 success; <= 0 fail
     */
    private static int getStatusHeight(Activity activity) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = activity.getResources().getDimensionPixelSize(i5);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }


    public static int getTotalHeightofListView(ListView listView) {
        ListAdapter mAdapter = listView.getAdapter();
        if (mAdapter == null) {
            return 0;
        }
        int totalHeight = 0;
        for (int i = 0; i < mAdapter.getCount(); i++) {
            View mView = mAdapter.getView(i, null, listView);
            mView.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            //mView.measure(0, 0);
            totalHeight += mView.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
        return totalHeight;
    }

    public static void jumpWebView(Activity activity,String url){

        GWWebViewActivity.openActivity(activity,url);
    }

    public static boolean jumpAPP(Activity activity,String packageName,Bundle bundle){
        if (activity == null){
            GWLog.e("GWAPP","activity null");
            return false;
        }

        if (bundle == null){
            bundle = new Bundle();
        }

        PackageManager pm = activity.getPackageManager();
        try {
            ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA);
            String appName = appInfo.loadLabel(activity.getPackageManager()) + "";
            PackageInfo pi = pm.getPackageInfo(activity.getPackageName(), 0);
            bundle.putString("AppName",appName);
            bundle.putString("packageName",pi.packageName);
            bundle.putString("game_id", SdkDomain.getInstance().getGameId());
            bundle.putString("game_name", SdkDomain.getInstance().getGameName());
            bundle.putString("game_appid", SdkDomain.getInstance().getGameAppId());
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        try {
            String activityClass = "com.genwan.voice.GWAuthActivity";
            ComponentName component = new ComponentName(packageName, activityClass);
            Intent intent = new Intent();
            intent.setComponent(component);
            intent.putExtras(bundle);
            activity.startActivity(intent);
            return true;
        }catch (Exception e){
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(AppStatusManager.getInstance().downUrl);
            intent.setData(content_url);
            activity.startActivity(intent);
            GWLog.e("GWSDK","没有安装跟玩游戏盒子");
            return false;
        }
    }

    /**
     * 是否是邮箱
     * @param regex
     * @param input
     * @return
     */
    public static boolean isMatch(final String regex, final CharSequence input) {
        return input != null && input.length() > 0 && Pattern.matches(regex, input);
    }

    public static boolean checkAppInstalled(Context context, String pkgName){
        if (TextUtils.isEmpty(pkgName)) {
            return false;
        }
        PackageManager manager = context.getPackageManager();
        List<PackageInfo> pkgList = manager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名
        //从pinfo中将包名字逐一取出，压入pName list中
        if(pkgList != null){
            for(int i = 0; i < pkgList.size(); i++){
                String pn = pkgList.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(pkgName);
    }


    /**
     * 调用第三方浏览器打开
     * @param context
     * @param url 要浏览的资源地址
     */
    public static void openBrowser(Context context, String url){
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            ToastUtil.show(context,"请下载浏览器");
        }
    }

    public static String MonthDay(String time,String geshi) {
        SimpleDateFormat sdr = new SimpleDateFormat(geshi);
        long i = Long.parseLong(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;

    }

    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            //wifi mac地址
            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            @SuppressLint("MissingPermission") String imei = tm.getDeviceId();
            if(!imei.isEmpty()){
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            @SuppressLint("MissingPermission") String sn = tm.getSimSerialNumber();
            if(!sn.isEmpty()){
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deviceId.toString();
    }


    public static void RestartApp(Context context){
        Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 1秒钟后重启应用
        System.exit(0);
    }



    /**
     * 调整图片大小
     *
     * @param bitmap
     * 源
     * 输出宽度
     * 输出高度
     * @return
     */
    public static Bitmap imageScale(Context context, Bitmap bitmap, int w, int h) {
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();
        int dst_w = dip2px(context, w);
        int dst_h = dip2px(context, h);
        float scale_w = ((float) dst_w) / src_w;
        float scale_h = ((float) dst_h) / src_h;
        Matrix matrix = new Matrix();
        matrix.postScale(scale_w, scale_h);
        Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,
                true);
        return dstbmp;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //输入身份证号 获得生日信息
    public static String getBirthday(String id){
        try {
            if (id.length() == 18){
                String year = id.substring(6, 10);// 截取年
                String month = id.substring(10, 12);// 截取月份
                String  day = id.substring(12, 14);// 截取天
                return year + month + day;
            }else if (id.length() == 15){
                String year = "19" + id.substring(6, 8);// 截取年
                String month = id.substring(8, 10);// 截取月份
                String  day = id.substring(10, 12);// 截取天
                return year + month + day;
            }
            else return "";
        }catch (Exception e){
            Log.e("获得生日信息异常",e.toString());
            return "";
        }
    }


    /**
     * 计算百分比
     */
    public static String getPercentage(int All,int surplus){
        NumberFormat numberFormat = NumberFormat.getInstance();
        DecimalFormat df = new DecimalFormat("0.00"); //百分比格式，后面不足2位的用0补齐
        String result = df.format(((float) surplus / (float) All) * 100);
        return result;
    }


    private static GWLoadDialog loadDialog;
    //显示加载弹窗
    public static void ShowLoadDialog(Context context){
        loadDialog = new GWLoadDialog(context, GWInflaterUtils.getIdByName(context, "style", "gw_my_dialog_style"));
        loadDialog.show();
    }

    //关闭加载弹窗
    public static void DissLoadDialog(){
        if (loadDialog!=null && loadDialog.isShowing()){
            loadDialog.dismiss();
        }
    }


    /**
     * 验证校验码，加载页面链接
     * @param activity
     * @param authCode
     * @param pageUrl
     */
    public static void loadUrl(Activity activity,String authCode,String pageUrl){
        String url = GWConstant.getInstance().getIpAddress().substring(0, GWConstant.getInstance().getIpAddress().indexOf("sdk/"))
                + pageUrl;
        String base64AuthCode = android.util.Base64.encodeToString(authCode.getBytes(), android.util.Base64.DEFAULT);
        String base64URL = android.util.Base64.encodeToString(url.getBytes(), Base64.DEFAULT);
        String location = GWConstant.getInstance().getCheckAuth() + "/auth_code/" + base64AuthCode  + "/redirect_url/" + base64URL;

        WebViewUtil.webView(activity, location);
    }

    /**
     * 得到图片字节流 数组大小
     * */
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    //小时转换成秒
    public static double getDouble(String str) {
        if (!TextUtils.isEmpty(str)) {
            return Double.parseDouble(str) * 60 * 60;
        } else {
            return 0.00;
        }
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isAppOnForeground(Activity activity) {
        ActivityManager activityManager = (ActivityManager) activity.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = activity.getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

}
